#include "stdafx.h"
#include "DBManager.h"
#include "sqlitelibrary.h"

using namespace std;

bool CFileManager::initialed = false;
CRITICAL_SECTION CFileManager::mDBFilesMapLock;
std::map<string, uintptr_t> CFileManager::mAllDBFiles;

CFileManager::CFileManager(std::string filename):mFileName(filename), mTableName(filename)
{
	//".db"
	if (mFileName.rfind(SQLITEEXTENSION) != mFileName.length() - strlen(SQLITEEXTENSION)) {//name without extension
		mFileName.append(SQLITEEXTENSION);
	}
	else {
		mTableName = mTableName.substr(0, mTableName.rfind(SQLITEEXTENSION));
	}
}

CFileManager::~CFileManager()
{
}

bool CFileManager::InitialGlobalResource()
{
	if (initialed)
		return true;

	initialed = true;
	InitializeCriticalSection(&mDBFilesMapLock);
	return initialed;
}

uintptr_t CFileManager::FindDBFile(std::string filename)
{
	uintptr_t obj = 0;
	EnterCriticalSection(&mDBFilesMapLock);

	std::map<string, uintptr_t>::iterator it = mAllDBFiles.find(filename);
	if (it != mAllDBFiles.end()) {
		obj = it->second;
	}

	LeaveCriticalSection(&mDBFilesMapLock);

	return obj;
}

bool CFileManager::FindAndAddDBFile(std::string filename, uintptr_t object)
{
	bool ret = false;
	EnterCriticalSection(&mDBFilesMapLock);

	std::map<string, uintptr_t>::iterator it = mAllDBFiles.find(filename);
	if (it == mAllDBFiles.end()) {
		mAllDBFiles[filename] = object;
		ret = true;
	}

	LeaveCriticalSection(&mDBFilesMapLock);

	return ret;
}

bool CFileManager::RemoveDBFile(std::string filename)
{
	bool ret = false;
	EnterCriticalSection(&mDBFilesMapLock);

	std::map<string, uintptr_t>::iterator it = mAllDBFiles.find(filename);
	if (it != mAllDBFiles.end()) {
		mAllDBFiles.erase(it);
		ret = true;
	}

	LeaveCriticalSection(&mDBFilesMapLock);

	return ret;
}

CSQLiteHandler::CSQLiteHandler() :mSession(nullptr)
{
	mSyncObj = CreateEvent(NULL, TRUE, FALSE, "CLiteConfig::mSyncObj");
}

CSQLiteHandler::~CSQLiteHandler()
{
	if (mSession != nullptr) {
		sqlite3_close(mSession);
		mSession = nullptr;
	}
	CloseHandle(mSyncObj);
}

bool CSQLiteHandler::OpenDB(std::string filename)
{
	return sqlite3_open(filename.c_str(), &mSession);;
}
